﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WxStockWinSvc.Models.Entities;
using System.Net;
using System.IO;
using System.Runtime.Serialization.Json;

namespace WxStockWinSvc.DALs.Http
{
    class DalGetIP
    {
        internal static IpEntity DoGetIP()
        {
            //【西西 2012-12-4-235513】此方法写到CommonUtility里面去。
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://pv.sohu.com/cityjson");
            req.Method = "GET";

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            string sResultJson = string.Empty;
            if (resp.StatusCode == HttpStatusCode.OK)
            {
                using (StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.GetEncoding("gbk")))
                    sResultJson = sr.ReadToEnd();
            }

            string sResult = sResultJson.Substring(sResultJson.IndexOf("{"), sResultJson.Length - sResultJson.IndexOf("{") - 1);

            DataContractJsonSerializer outDs = new DataContractJsonSerializer(typeof(IpEntity));
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(sResult)))
            {
                IpEntity ipEntity = outDs.ReadObject(ms) as IpEntity;
                ipEntity.OriginalJson = sResultJson;
                return ipEntity;
            }
        }
    }
}
